from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, CreateModelMixin, ListModelMixin
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import OrderingFilter
from apps.minapp import models
from utils.tencent.oss import get_credential
from apps.web.forms.goods import CoverAddsForm


class MenuSerializer(serializers.ModelSerializer):
    src = serializers.CharField()

    class Meta:
        model = models.Cover
        fields = "__all__"


class ShopSerializer(serializers.ModelSerializer):
    icon = serializers.CharField()

    class Meta:
        model = models.Window
        fields = "__all__"


class MenuPageNumberPagination(PageNumberPagination):
    page_query_param = 'page'
    page_size_query_param = 'size'
    max_page_size = 20


class MenuView(ModelViewSet):
    authentication_classes = []
    serializer_class = MenuSerializer
    filter_backends = [OrderingFilter]
    pagination_class = MenuPageNumberPagination
    # pagination_class = CursorPagination
    ordering = ['-id', '-sales', 'price']

    def get_queryset(self):
        queryset = models.Cover.objects.all()
        # 商品名称
        name = self.request.query_params.get('query', None)
        print(name)
        if name != "" and name is not None:
            print(name, "ppp")
            queryset = queryset.filter(name__contains=name)
        return queryset

    def update(self, request, *args, **kwargs):
        print(request.data)
        print(request.user, request.auth)
        data = request.data
        Covers = models.Cover.objects.all()
        Covers.filter(id=data['id']).update(**data)
        return Response({'code': 0, 'msg': '修改成功'})

    def create(self, request, *args, **kwargs):
        print(request.data)
        data = request.data
        Covers = models.Cover.objects.all()
        cover = Covers.create(**data)
        return Response({'code': 0, 'id': cover.id})

    def destroy(self, request, *args, **kwargs):
        print(args)
        print(kwargs)
        id = kwargs['pk']
        cover = models.Cover.objects.get(id=id)
        cover.delete()
        return Response({'code': 0, "msg": '删除成功'})


# class DetailSerializer(serializers.ModelSerializer):
#
#
#
# class DetailView(ModelViewSet):
#     queryset = models.Detail.objects.all()
#     serializer_class = DetailSerializer


class OssCredentialView(APIView):

    def get(self, request, *args, **kwargs):
        return Response(get_credential())


class TestView(APIView):

    def post(self, request, *args, **kwargs):
        image_object_list = request.FILES.getlist('src')
        print(image_object_list)
        for index in range(len(image_object_list)):
            image_object = image_object_list[index]
            if not image_object:
                continue
            form = CoverAddsForm(data=request.POST, files=request.FILES)
            if form.is_valid():
                instance = form.save()
                return Response({
                    'data': {
                        # 'list_url': reverse(viewname='menu1'),
                        # 'image_url': reverse('auction_item_image_add', kwargs={'item_id': instance.id}),
                        # 'detail_url': reverse('auction_item_list', kwargs={'goods_id': })
                    }
                })


class UploadImageView(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        return Response("ok")


class CoverSerializer(serializers.ModelSerializer):
    src = serializers.CharField()

    class Meta:
        model = models.Cover
        fields = "__all__"


class SrcSerialzer(serializers.ModelSerializer):
    src = serializers.CharField()

    class Meta:
        model = models.DetailSrc
        fields = ['src']


class DetailSerializer(serializers.ModelSerializer):
    cover = CoverSerializer()
    shop = ShopSerializer()
    detailsrc = SrcSerialzer(many=True)

    class Meta:
        model = models.Detail
        fields = "__all__"
        depth = 1

    def update(self, instance, validated_data):
        # print(validated_data)
        print('instance', instance)
        print('com', instance.composition)
        cover_id = self.data['cover']['id']
        shop_id = self.context['request'].data['shop']['id']
        detailsrcs = self.context['request'].data['detailsrc']
        originsrcs = instance.detailsrc
        print(originsrcs.all())
        for src in detailsrcs:
            try:
                detailsrc = models.DetailSrc.objects.all().get(src=src['src'])
            except models.DetailSrc.DoesNotExist as e:
                models.DetailSrc.objects.all().create(src=src['src'], detail=instance)
                print(e)
        detailsrcs_srcs = [item['src'] for item in detailsrcs]
        for item in originsrcs.all():
            if item.src not in detailsrcs_srcs:
                item.delete()
        cover = models.Cover.objects.get(id=cover_id)
        cover.__dict__.update(**validated_data['cover'])
        cover.save()
        shop = models.Window.objects.get(id=shop_id)
        # print('shopid=' + str(shop_id))
        # print(shop)
        instance.shop = shop
        instance.cover = cover
        instance.composition = validated_data['composition']
        instance.rate = validated_data['rate']
        instance.save()
        return instance

    def create(self, validated_data):
        print(validated_data['cover'])
        cover = models.Cover(**validated_data['cover'])
        cover.save()
        shop_id = self.context['request'].data['shop']['id']
        shop = models.Window.objects.get(id=shop_id)
        detailsrcs = self.context['request'].data['detailsrc']

        detail = models.Detail.objects.all().create(cover=cover, composition=validated_data['composition'], shop=shop,
                                                    rate=validated_data['rate'])
        detail.save()
        for src in detailsrcs:
            models.DetailSrc.objects.all().create(src=src['src'], detail=detail)
        return detail


class DetailView(ListModelMixin,RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, GenericViewSet):
    authentication_classes = []
    queryset = models.Detail.objects.all()
    serializer_class = DetailSerializer

    def get_queryset(self):
        print(self.request.body)
        queryset = models.Detail.objects.all()
        return queryset


class ShopView(ListModelMixin, GenericViewSet):
    authentication_classes = []
    queryset = models.Window.objects.all()
    serializer_class = ShopSerializer
    filter_backends = [OrderingFilter]
    ordering = 'id'
